package com.zl.customer.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 检查是否登录
 * @author suke
 * @create 2021-07-12 14:01
 */
//@WebFilter(filterName = "CheckLoginFilter",urlPatterns = "/*")
public class CheckLoginFilter implements Filter {
    private static String[]  excludePath = {".html",".gif",".png",".jpg",".css",".js","index.jsp",
                                                "login.jsp","frame.jsp","top.jsp","welcome.jsp",
                                                    "login.action","register.action","favicon.ico"};

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //得到访问的url
        String requestURI = request.getRequestURI();

        if(containsStr(requestURI)){
            chain.doFilter(request, response);  //放行
        }else{  //不包含
            //判断是否登录
            HttpSession session = request.getSession();
            if(session.getAttribute("loginUser") != null){  //登录  从session获取 loginUser 如果有表示已登录, 如果没有表示未登录
                chain.doFilter(request, response);  //放行
            }else{ //未登录
                //把用户访问的url保存到session
              // session.setAttribute("jumpUrl",requestURI);

                //重定向
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        }
    }

    /**
     *  判断 path 是否包含excludePath中内容
     * @return  true 包含,  false 不包含
     */
    private boolean  containsStr(String path){
        ///css/test.css
        for (String str: excludePath){
            //忽略大小写
            if(path.toUpperCase().endsWith(str.toUpperCase())){
                return true;
            }
        }
        return false;
    }




    public void init(FilterConfig config) throws ServletException {}

    public void destroy() {}

}
